package com.demo.crm.controller;

import com.arvato.crm.common.JsonUtil;
import com.arvato.crm.common.ValidErrorUtil;
import com.arvato.crm.model.entity.Manager;
import com.demo.crm.model.AjaxInfo;
import com.demo.crm.model.UserToken;
import com.demo.crm.service.LogService;
import com.demo.crm.service.ManagerService;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author tanshuai
 */
@Controller
@RequestMapping("/admin")
public class ManagerController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private LogService logService;

    @RequestMapping("/edit")
    @ResponseBody
    public AjaxInfo edit(@Valid Manager manager, Errors errors) {
        if (errors.hasErrors()) {
            return new AjaxInfo(false, ValidErrorUtil.toString(errors));
        }

        if (manager.getPassword().length() != 32) {
            manager.setPassword(DigestUtils.md5Hex(manager.getPassword()));
        }

        return managerService.edit(manager) ? AjaxInfo.SUCCESS : AjaxInfo.EXCEPTION;
    }

    /**
     * 跳转到首页前进行的初始化操作
     */
    @RequestMapping("/init")
    public String init(HttpServletRequest request) {
        UserToken userToken = UserToken.getUserToken(request);

        // 重新查询该用户的权限配置
        Manager manager = managerService.findByName(((Manager) userToken.getPrincipal()).getName());
        userToken.setPrincipal(manager);

        request.getSession().setAttribute("menus", JsonUtil.toJson(managerService.getMenus(manager)));
        request.setAttribute("logs", logService.getByManager(manager));
        return "jsp/manage/index.jsp";
    }
}
